import prisma from "@/db/prisma";
import {
  CreateRoleResponse,
  GetRoleByIdResponse,
  UpdateRoleResponse,
} from "@/types/api";
import { Prisma } from "@prisma/generated-client";

export class RoleService {
  async create(data: Prisma.RoleCreateInput): Promise<CreateRoleResponse> {
    return prisma.role.create({
      data,
    });
  }

  async findOne(roleId: number): Promise<GetRoleByIdResponse> {
    return prisma.role.findUnique({
      where: { id: roleId, deletedAt: null },
    });
  }

  async update(
    roleId: number,
    data: Prisma.RoleUpdateInput
  ): Promise<UpdateRoleResponse> {
    return prisma.role.update({
      where: { id: roleId },
      data,
    });
  }

  async delete(roleId: number) {
    await prisma.role.update({
      where: { id: roleId },
      data: { deletedAt: new Date() },
    });
    return true;
  }

  async page(
    pageNum: number,
    pageSize: number,
    keywords?: string,
    orderBy?: Prisma.RoleCountOrderByAggregateInput
  ) {
    const where: Prisma.RoleWhereInput = {
      deletedAt: null,
      OR: keywords
        ? [{ name: { contains: keywords } }, { remark: { contains: keywords } }]
        : undefined,
    };

    if (!orderBy) {
      orderBy = {
        createdAt: "desc",
      };
    }

    return prisma.$transaction(async (prisma) => {
      const total = await prisma.role.count({ where });
      const data = await prisma.role.findMany({
        skip: (pageNum - 1) * pageSize, // 跳过 (页码 - 1) * 每页数量 的记录
        take: pageSize, // 获取 pageSize 数量的记录
        where,
        orderBy,
      });

      return { data, total };
    });
  }
}
